const Ajax = require('robe-ajax');
import Constants from './Constants'

import {message} from 'antd';

const timeout = 30000;//30秒

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */

let errCount = 0;

export default function request(url, options) {
    options.data = { ...options.data, _channelType: 'ajax' };
    let res = {
        url,
        method: 'get',
        timeout,
        data: {},
        dataType: 'JSON',
        headers: { [Constants.ACJSESSIONID]: sessionStorage.getItem(Constants.ACJSESSIONID) },
        traditional: true,
        xhrFields: {
            withCredentials: true
        },
        ...options
    };
    return Ajax.ajax(res).then(data => {
        if (data.resultCode !== "ok") {
            message.error(data.content?`${data.errMessage},${data.content}`:`${data.errMessage}`);
            if (data.resultCode === 'SESSION_ERROR') {
                setTimeout(() => 
                    document.location.href = "/login"
                , 1000);
            }
        }
        return { data };
    }).catch(err => {
        err.abort();//终止请求
        message.error("服务器连接失败");
    });
}


export function requestString(url, options) {
    options.data[Constants.CHANNEL_TYPE] = Constants.AJAX;
    let res = {
        url,
        method: 'get',
        timeout,
        data: "",
        contentType: "application/json",
        dataType: 'JSON',
        headers: { [Constants.ACJSESSIONID]: sessionStorage.getItem(Constants.ACJSESSIONID) },
        xhrFields: {
            withCredentials: true
        },
        ...options
    };
    res.data = JSON.stringify(options.data);
    return Ajax.ajax(res).then(data => {
        if (data.resultCode !== "ok") {
            message.error(data.content?`${data.errMessage},${data.content}`:`${data.errMessage}`);
            if (data.resultCode === 'SESSION_ERROR') {
                setTimeout(() => 
                    document.location.href = "/login"
                , 1000);
            }
        }
        return { data };
    }).catch(err => {
        err.abort();//终止请求
        message.error("服务器连接失败");
    });
}
